<template>
  <div class="app-container">
    <el-row style="margin-bottom: 10px;">
      <el-button class="pan-btn success-btn" v-if="isReregist" @click="submit" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
        {{ isUpdate ? '重新发送' : ('发送至' + fromUserName) }}
      </el-button>
      <el-button class="pan-btn success-btn" v-if="sendAndGetBtn" @click="showGet" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
        发送并取样
      </el-button>
      <el-button class="pan-btn success-btn" v-if="sendBtn && !sendAndGetBtn" @click="submit" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
        发送
      </el-button>
      <el-tooltip effect="dark" :content="isFullLast ? '不填充' : '自动填充'" placement="top">
        <el-switch
          :disabled="fullLastDisabled"
          style="float: right;
          margin-right: 40px;
          margin-top: 8px;"
          v-model="isFullLast"
          @change="changeFullLast"
          active-color="#7cbd36"
          inactive-color="#ff4949"
          inactive-text="上一单">
        </el-switch>
      </el-tooltip>
    </el-row>

    <el-card shadow="hover" class="card2">
      <el-form ref="dataForm" :model="dataForm" label-width="80px">
        <el-form-item label="品名:" prop="productName">
          <span slot="label">品&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>
          <el-form :model="product" v-if="product != ''" :inline="true">
            <el-form-item>
              {{product.productName}}
            </el-form-item>
            <el-form-item label="物料编码:">
              {{product.productGmp}}
            </el-form-item>
            <el-form-item label="货品规格:">
              <span v-html="product.productSpec"></span>
            </el-form-item>
            <br />
            <el-form-item label="贮存条件:">
             <el-select v-model="checkList.storageConditions" size="small">
               <el-option v-for="storage in storageConditions" :key="storage.id" :label="storage.val" :value="storage.val" />
              </el-select>
            </el-form-item>
            <br />
            <el-form-item>
              <el-button
                :disabled="isReregist"
                type="info"
                class="pan-btn info-btn"
                @click="showProductSelect"
                size="mini">
                重新选择
              </el-button>
            </el-form-item>
          </el-form>
          <el-button
            v-if="product == ''"
            type="info"
            class="pan-btn info-btn"
            @click="showProductSelect"
            size="mini">
            请选择
          </el-button>
        </el-form-item>

        <el-form-item label="批号:" prop="batchNum">
          <span slot="label">批&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span>
          <el-row style="width: 100%;">
            <el-col :span="11">
              <el-input id="batchNum" :disabled="isDisable" v-model="checkList.batchNumPrefix" @change="setBatchNum" placeholder="批号" size="small" style="width: 100%;" />
            </el-col>
            <div>
              <el-col class="line" :offset="1" :span="1">-</el-col>
              <el-col :span="11">
                <el-input v-model="checkList.batchNumSuffix" @change="setBatchNum" placeholder="批号后缀" size="small" style="width: 100%;" />
              </el-col>
            </div>
          </el-row>
        </el-form-item>

        <el-form-item label="生产工序:" prop="procedureId">
          <el-select id="procedureId" :disabled="isDisable" v-model="dataForm.procedure" value-key="procedureId" @change="setProcedure" filterable placeholder="生产工序" style="width: 100%;" size="small">
            <el-option
              v-for="item in procedureList"
              :key="item.procedureId"
              :label="item.procedureName"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="请验目的:" prop="isTest">
          <el-radio-group :disabled="isDisable" @change="changeIsTest" v-model="checkList.isTest" size="small">
            <el-radio-button :label="0">常规检验</el-radio-button>
            <el-radio-button :label="1">留样或稳考</el-radio-button>
            <el-radio-button :label="2">只稳考不留样</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="请检项目:" prop="isAllTest" v-if="product != '' && checkList.isTest == 0">
          <div v-if="allItems.length == 0" style="color: #F56C6C;">
            <div v-if="noItem">
              该货品绑定的质量标准中没有对应的项目，请检查该货品名称和项目名称使其对应
            </div>
            <div v-else style="color: #F56C6C;">
              请添加此货品的检验标准
            </div>
          </div>

          <div v-else>
            <el-radio-group v-model="checkList.isAllTest" @change="changeItems" size="small">
              <el-radio-button :label="0">全检</el-radio-button>
              <el-radio-button :label="1">其他</el-radio-button>
            </el-radio-group>
            <el-button
              style="margin-left: 20px;"
              type="info"
              class="pan-btn info-btn"
              @click="showStandardDrawer"
              size="mini">
              查看项目
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="生产车间:" prop="workshopId">
          <el-select id="workshopId" v-model="dataForm.workshop" value-key="workshopId" @change="setWorkshop" filterable placeholder="生产车间" style="width: 100%;" size="small">
            <el-option
              v-for="item in workshopList"
              :key="item.workshopId"
              :label="item.workshopName"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="生产日期:" prop="productionDate">
          <el-date-picker
            id="productionDate"
            v-model="zcList.productionDate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            style="width: 100%;"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss"
            size="small">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="批量:" prop="batchQuantity">
          <span slot="label">批&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;量:</span>
          <el-input id="batchQuantity" v-model="zcList.batchQuantity" @change="setBatchQuantity" placeholder="批量(数值)" size="small" style="width: 55%;">
            <el-select id="batchUnitId" @change="setBatchUnit" value-key="unitId" v-model="dataForm.batchUnit" slot="append" placeholder="单位" style="width: 100px;">
              <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
            </el-select>
          </el-input>
        </el-form-item>

        <el-form-item label="请验日期:" prop="registCheckDate">
          <el-date-picker
            id="registCheckDate"
            v-model="checkList.registCheckDate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            style="width: 100%;"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss"
            size="small">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="请验人:" prop="registCheckUserId">
          <span slot="label">请&nbsp;&nbsp;验&nbsp;&nbsp;人:</span>
          {{checkList.registCheckUserName}}
        </el-form-item>

        <el-form-item label="备注:" prop="remark">
          <span slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注:</span>
          <el-input v-model="checkList.remark" placeholder="备注" size="small"/>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
      title="取样"
      :visible.sync="getVisible"
      :before-close="closeGet"
      :close-on-click-modal="false"
      width="50%">
      注：此操作会记录在《取样台账记录》
      <el-row>
        <el-col :span="24">
          <el-card>
            <el-form>
              <el-form-item prop="getQuantity">
                <el-input v-model="checkList.getQuantity" placeholder="取样量(数值)">
                  <el-select @change="setGetUnit" value-key="unitId" v-model="checkList.getUnit" slot="append" placeholder="单位" style="width: 100px;">
                    <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
                  </el-select>
                </el-input>
                <el-input style="width: 100%; margin-top: 10px;" v-model="checkList.getRoom" placeholder="取样位置" />
                <el-date-picker
                  v-model="checkList.getDate"
                  align="right"
                  type="date"
                  placeholder="取样日期"
                  :clearable="false"
                  style="width: 100%; margin-top: 10px;"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeGet">取 消</el-button>
        <el-button class="pan-btn primary-btn" type="primary" @click="getOk">确 定</el-button>
    	</span>
    </el-dialog>

    <product-select
      @getProduct="getProduct"
      @showProductSelect="showProductSelect"
      :childDataForm="childDataForm"
      v-if="productSelectVisible" />

    <standard-drawer
      ref="standard"
      :childDataForm="childDataForm"
      @close="closeStandardDrawer"
      @getStandard="getStandard"
      v-if="standardDrawerVisible" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { CODE_OK } from '@/common/js/config'
  import { isNumber,isLetterOrNumber } from '@/common/js/validate'
  import { isBlank,parseTime,dateCompare } from '@/common/js/utils'
  import ProductSelect from '@/views/modules/base/product-select'
  import StandardDrawer from '@/views/modules/base/standard-drawer'
  import {
    getProcedureList,
    getWorkshopList,
    getUnitList,
    registCheck,
    getRegistCheckInfo,
    getLastCheckForRegist,
    checkBatchNum
  } from '@/api/check'
  import { getStandardByProductId,getStandardById } from '@/api/standard'
  import { getStorageConditionsByProductId,getProductPackSpecsByProductId,getProductProcessOne } from '@/api/product'
  export default {
    name: 'registcheck401',
    components: {
    	ProductSelect,StandardDrawer
    },
    data() {
      return {
        storageConditions:[],
        printCheckVersion: '01',
        isFullLast: false,
        isReregist: false,
        isDisable: false,
        isUpdate: false,
        fromUserName: null,
        fromStatus: null,
        checkReturnId: null,
        productSelectVisible: false,
        standardDrawerVisible: false,
        getVisible: false,
        rag: false,
        productPackSpecList: [],
        originalProcedureList: [],
        procedureList: [],
        workshopList: [],
        unitList: [],
        standard: '',
        allItems: [],
        nowStandard: null,
        nextStandard: null,
        isUpgradeStandard: 1,
        noItem: false,
        items: [],
        checkList: {
          checkTypeId: 4,
          checkTypeName: '中间品',
          isTest: '',
          isAllTest: '',
          isMerge: '',
          status: 1,
          getUnitId: '',
          getUnitName: '',
          registCheckDate: ''
        },
        zcList: {
          procedureId: ''
        },
        product: '',
        dataForm: {
          procedure: '',
          workshop: '',
          batchUnit: ''
        },
        childDataForm: '',
        itemFilterException: false
      }
    },
    created() {
      if (!isBlank(this.$route.query.checkId)) {
        this.isReregist = true
      }
      this.init()
      this.getZcInfo()
      //单位默认袋
      this.dataForm.batchUnit = '袋'
      this.zcList.batchUnitId = 13
      this.zcList.batchUnitName = "袋"
    },
    computed: {
      isMerge() {
        return this.product == '' ? false : this.product.haveProcess == 0 ? true : false
      },
      ...mapGetters([
         'userInfo'
      ]),
      fullLastDisabled() {
        return this.allItems.length == 0 || this.product == '' || isBlank(this.zcList.procedureId) || this.isUpdate
      },
      sendBtn() {
        return !this.isReregist && !this.isUpdate && this.userInfo.roles.filter(r => {return r.roleName == '请验'}).length > 0
      },
      sendAndGetBtn() {
        return !this.isReregist && !this.isUpdate && (this.userInfo.roles.filter(r => {return r.roleName == '取样' || r.roleName == '信息' || r.roleName == '请取样'}).length > 0 || this.userInfo.userId == 1)
      }
    },
    methods: {
      initStorageConditions(productId){
        let params = {
          productId:productId
        }
        getStorageConditionsByProductId(params).then(res=>{
          if (res.code === CODE_OK) {
          	this.storageConditions = res.storageConditions
          	if (this.storageConditions.length == 0) {
          		this.$message.info("此货品未在货品管理中添加贮存条件")
          	}
          } else {
          	this.$message.error(res.msg)
          }
        });
      },
      init() {
        if (this.isReregist) {
          const params = {
            checkId: this.$route.query.checkId,
            content: 'zc'
          }
          getRegistCheckInfo(params).then(res => {
            if (res.code === CODE_OK) {
              this.fillData(res.info)
              this.setReregistInfo()
            }else{
              this.$message({
                message: res.msg,
                type: 'error',
                duration: 1500,
                onClose: () => {
                  window.history.go(-1)
                }
              })
            }
          })
        }else{
          this.setRegistInfo()
        }
      },
      setRegistInfo() {
        this.checkList.registCheckDepartmentId = this.userInfo.departmentId
        this.checkList.registCheckDepartmentName = this.userInfo.departmentName
        this.checkList.registCheckUserId = this.userInfo.userId
        this.checkList.registCheckUserName = this.userInfo.name
      },
      fillData(info) {
        let checkList = info.checkList
        this.initStorageConditions(checkList.productId)
        let zcList = info.zcList
        this.checkList = JSON.parse(JSON.stringify(checkList))
        this.zcList = JSON.parse(JSON.stringify(zcList))
        this.dataForm.procedure = {
          procedureId: zcList.procedureId,
          procedureName: zcList.procedureName
        }
        this.dataForm.workshop = {
          workshopId: zcList.workshopId,
          workshopName: zcList.workshopName,
        }
        this.dataForm.batchUnit = {
          unitId: zcList.batchUnitId,
          unitName: zcList.batchUnitName
        }
        // 如果是修改或者重新发起
        if (this.isReregist) {
          this.getProduct(info.product, 'noSetWorkshop', 'noGetStandard')
          this.product.haveProcess = checkList.isMerge
          // 如果是检验的
          if (this.checkList.isTest == 0) {
            this.standard = info.baseStandard
            this.allItems = this.standard.items
            this.items = info.items
            this.checkList.isAllTest = checkList.isAllTest
          }else{
            // 留样
            this.checkList.isAllTest = 1
          }
          this.isDisable = checkList.isMerge == 0 ? true : false
        }else{
          // 否则是获取上一单，进一步判断是否是检验
          if (this.checkList.isTest == 0) {
            this.checkList.isAllTest = null
            this.items = []
            if (this.isFullLast && this.standard.insideInspectionStandardId != info.standard.insideInspectionStandardId) {
              if (checkList.isAllTest == 0) {
                this.checkList.isAllTest = 0
                this.items = JSON.parse(JSON.stringify(this.allItems))
              }else{
                this.$message.error("标准已升级，请自己选择检验项目")
              }
            }else{
              if (checkList.isAllTest == 0) {
                this.checkList.isAllTest = 0
                this.items = JSON.parse(JSON.stringify(this.allItems))
              }else{
                // 按名字选择
                for (let i=0,j=info.items.length; i<j; i++) {
                  let it = this.allItems.find(v => v.inspectionItemName == info.items[i].inspectionItemName)
                  if (isBlank(it)) {
                    this.$message.error("项目未找到，请自行选择")
                    this.checkList.isAllTest = null
                    this.items = []
                    return
                  }else{
                    this.items.push(JSON.parse(JSON.stringify(it)))
                  }
                }
                this.checkList.isAllTest = 1
              }
            }
          }else{
            this.checkList.isAllTest = 1
          }
        }
        this.setRegistInfo()
      },
      setReregistInfo() {
        if (this.$route.query.checkReturnId != 0) {
          this.fromUserName = this.$route.query.fromUserName
          this.fromStatus = this.$route.query.fromStatus
          this.checkReturnId = this.$route.query.checkReturnId
        }else{
          this.isUpdate = true
        }
      },
      getZcInfo() {
        getProcedureList().then(res => {
          if (res.code === CODE_OK) {
            this.procedureList = res.list
            this.originalProcedureList = JSON.parse(JSON.stringify(this.procedureList))
          }else{
            this.$message.error(res.msg)
          }
        })
        getWorkshopList().then(res => {
          if (res.code === CODE_OK) {
            this.workshopList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getUnitList().then(res => {
          if (res.code === CODE_OK) {
            this.unitList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      submit() {
        this.checkList.printCheckVersion = this.printCheckVersion
        this.checkList.isMerge = this.isMerge ? 0 : 1
         if (this.formVerify()) {
           let data = {
             rag: this.rag,
             content: 'zc',
             fromStatus: this.fromStatus,
             checkReturnId: this.checkReturnId,
             checkList: this.checkList,
             zcList: this.zcList,
             product: this.product,
             standard: this.standard,
             items: this.items
           }
           registCheck(data).then(res => {
             if (res.code === CODE_OK) {
               this.$message({
                 message: '提交成功',
                 type: 'success',
                 duration: 1000,
                 onClose: () => {
                  window.history.go(-1)
                 }
               })
             }else if(res.code === 999) {
               this.$confirm(res.msg, {
                 confirmButtonText: '是',
                 cancelButtonText: '否'
               }).then(async () => {
                 this.$set(data,'pass','yes')
                 registCheck(data).then(res => {
                   if (res.code === CODE_OK) {
                     this.$message({
                       message: '提交成功',
                       type: 'success',
                       duration: 1000,
                       onClose: () => {
                        window.history.go(-1)
                       }
                     })
                   }else{
                     this.$message.error(res.msg)
                   }
                 })
               }).catch(() => {})
             }else{
               this.$message.error(res.msg)
             }
           })
         }
      },
      changeFullLast() {
        if (this.isFullLast) {
          const params = {
            content: 'zc',
            productId: this.product.productId,
            procedureId: this.zcList.procedureId
          }
          getLastCheckForRegist(params).then(res => {
            if (res.code === CODE_OK) {
              this.fillData(res.info)
              this.setRegistInfo()
            }else{
              this.$message.error(res.msg)
              this.isFullLast = false
            }
          })
        }else{
          //初始化

        }
      },
      formVerify() {
        if (isBlank(this.checkList.storageConditions)) {
          this.$message.error('请选择货品贮存条件')
          return false
        }
        if (isBlank(this.product)) {
          this.$message.error('请选择货品')
          return false
        }
        if (isBlank(this.zcList.procedureId)) {
          this.$message.error('请选择工序')
          $("#procedureId").css({"border-color" : "#D08585"})
          return false
        }
        $("#procedureId").removeAttr('style')
        if (this.checkList.isTest === '') {
          this.$message.error('请选择请验目的')
          return false
        }
        if (this.checkList.isTest == 0) {
          if (this.items.length == 0) {
            this.$message.error('请选择请验项目')
            return false
          }
        }
        if (isBlank(this.zcList.workshopId)) {
          this.$message.error('请选择生产车间')
          $("#workshopId").css({"border-color" : "#D08585"})
          return false
        }
        $("#workshopId").removeAttr('style')
        if (isBlank(this.checkList.batchNum)) {
          this.$message.error('请输入批号')
          $("#batchNum").css({"border-color" : "#D08585"})
          return false
        }
        $("#batchNum").removeAttr('style')
        if (isBlank(this.zcList.productionDate)) {
          this.$message.error('请选择生产日期')
          $("#productionDate").css({"border-color" : "#D08585"})
          return false
        }
        $("#productionDate").removeAttr('style')
        if (isBlank(this.zcList.batchQuantity)) {
          this.$message.error('请输入批量(数值)')
          $("#batchQuantity").css({"border-color" : "#D08585"})
          return false
        }
        $("#batchQuantity").removeAttr('style')
        if (isBlank(this.zcList.batchUnitId)) {
          this.$message.error('请选择批量(单位)')
          $("#batchUnitId").css({"border-color" : "#D08585"})
          return false
        }
        $("#batchUnitId").removeAttr('style')
        if (isBlank(this.checkList.registCheckDate)) {
          this.$message.error('请选择请检日期')
          $("#registCheckDate").css({"border-color" : "#D08585"})
          return false
        }
        $("#registCheckDate").removeAttr('style')
        if (isBlank(this.checkList.registCheckDepartmentId) || isBlank(this.checkList.registCheckUserId)) {
          this.$message.error('登录过期,请刷新页面')
          return false
        }
        return true
      },
      changeItems() {
        if (this.checkList.isAllTest == 0) {
          this.items = JSON.parse(JSON.stringify(this.allItems))
        }else{
          this.items = []
          this.showStandardDrawer()
        }
      },
      showProductSelect() {
        this.childDataForm = {
          checkTypeId: this.checkList.checkTypeId
        }
      	this.productSelectVisible = !this.productSelectVisible
      },
      getProduct(product, opt1, opt2) {
        this.product = product
        const params = {
          productId: product.productId
        }
        if (opt1 != 'noSetWorkshop') {
          this.dataForm.workshop = {
            workshopId: product.workshopId,
            workshopName: product.workshopName
          }
        }
        this.setWorkshop()
        if (opt2 != 'noGetStandard') {
          this.initStandard()
          getStandardByProductId(params).then(res => {
            if (res.code === CODE_OK) {
              this.afterGetStandard(res)
            }else{
              this.$message.error(res.msg)
            }
          })
        }
        this.initStorageConditions(product.productId)
        getProductPackSpecsByProductId(params).then(res => {
          if (res.code === CODE_OK) {
            this.productPackSpecList = res.productPackSpecs
            if (this.productPackSpecList.length == 0) {
              // this.$message.error("请联系货品管理员添加此货品的包装规格")
            }else{
              //包装规格默认第一个
              this.checkList.productPackSpec = this.productPackSpecList[0].productPackSpec
            }
          }else{
            this.$message.error(res.msg)
          }
        })
        if (this.isMerge) {
          const params = {
            productId: product.productId
          }
          getProductProcessOne(params).then(res => {
            if (res.code === CODE_OK) {
              let procedureIds = res.process.procedureIds
              let procedureIdsArr = procedureIds.split(",")
              let tempProcedureList = []
              for (let id of procedureIdsArr) {
                for (let p of this.originalProcedureList) {
                  if (id == p.procedureId && tempProcedureList.indexOf(p) == -1) {
                    tempProcedureList.push(p)
                    break
                  }
                }
              }
              this.procedureList = tempProcedureList
            }else{
              this.$message.error(res.msg)
            }
          })
        }else{
          this.procedureList = JSON.parse(JSON.stringify(this.originalProcedureList))
        }
      },
      afterGetStandard(res) {
        this.allItems = res.standard.items
        if (this.allItems.length == 0) return
        this.itemFilter()
        if (!this.isReregist) {
          this.standard = res.standard
          //保存两个标准
          this.nowStandard = JSON.parse(JSON.stringify(res.standard))
          if (!isBlank(res.waitBatch)) {
            this.nextStandard = res.waitBatch
          }
        }
        if (this.itemFilterException) {
          this.showStandardDrawer()
          setTimeout(() => {
            this.$message({
              message: '可能存在检验项目过滤，但是并不成功，请联系管理员或者手动选择项目',
              type: 'error',
              duration: 5000
            })
          },200)
        }
      },
      itemFilter() {
        //可能要过滤
        if (this.product.productName.indexOf('(') > -1 && this.product.productName.indexOf(')') > -1) {
          let filterArr = ["(颗粒)","(素片)","(包衣片)","(胶囊)","(总混粉末)","(总混颗粒)","(总混)","(修饰层)","(载药层)","(胶囊中间体)"]
          for (let i=0,j=filterArr.length; i<j; i++) {
            let f = filterArr[i]
            //如果存在，则过滤
            if (this.product.productName.indexOf(f) > -1) {
              let tempItems = []
              for (let item of this.allItems) {
                if (item.inspectionItemName.indexOf(f) > -1) {
                  tempItems.push(item)
                }
              }
              this.allItems = tempItems
              this.noItem = this.allItems.length == 0
              break
            }
            //如果不存在，提醒，并打开项目选择
            if (i==j-1) {
              this.itemFilterException = true
            }
          }
        }
      },
      showStandardDrawer() {
        this.childDataForm = {
          product: this.product,
          standard: this.standard,
          allItems: this.allItems,
          checkedItems: this.items
        }
        this.standardDrawerVisible = !this.standardDrawerVisible
      },
      closeStandardDrawer() {
        this.childDataForm = ''
        this.standardDrawerVisible = !this.standardDrawerVisible
      },
      getStandard(standardObj) {
        this.items = standardObj.checkedItems
        this.checkList.isAllTest = standardObj.isAllTest
      },
      initStandard() {
        this.standard = ''
        this.allItems = []
        this.items = []
        this.checkList.isAllTest = ''
      },
      //根据object赋值id和name
      changeIsTest() {
        if (this.checkList.isTest == 1 || this.checkList.isTest == 2) {
          this.checkList.isAllTest = 1
        }
      },
      getParentStandard() {
        const params = {
          standardId: this.standard.parentId
        }
        getStandardById(params).then(res => {
          if (res.code === CODE_OK) {
            this.initStandard()
            this.afterGetStandard(res)
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      chooseStandard() {
        let s = this.standard
        // 如果有生效批号标志和父级标准，并且当前批号小于生效批号
        if (!isBlank(s.effectiveBatchNum) && !isBlank(s.parentId) && this.conditionOnBatch(s.effectiveBatchNum, this.checkList.batchNumPrefix.substr(-6))) {
          this.getParentStandard()
          return true
        }
        return false
      },
      setBatchNum() {

        //if (!/^[A-Z]{0,2}\d{6}$/.test(this.checkList.batchNumPrefix)) {
          //this.$message.error('批号前缀只允许2位字母和6位数字')
          //this.checkList.batchNumPrefix = null
          //return
        //}
        // 选择是否需要改变标准
        // 如果当前选中标准是按批号升级的，并且已经生效，那么如果此单的批号小于升级的批号，
        // 此单就应该用老标准，但是当前的货品只绑定了新标准，那么就需要重新选择老标准
        // 如果没进行改变标准，那么还需要判断是否升级标准
        if (!this.chooseStandard()) {
          //检查是否需要升级标准
          if (!isBlank(this.checkList.batchNumPrefix) && !isBlank(this.nextStandard)) {
            if (this.conditionOnBatch(this.checkList.batchNumPrefix.substr(-6), this.nextStandard.effectiveBatchNum)) {
              //升级，将下一个标准赋值给显示的标准
              this.isUpgradeStandard = 0
              this.standard = JSON.parse(JSON.stringify(this.nextStandard))
              this.allItems = JSON.parse(JSON.stringify(this.nextStandard.items))
              if (this.checkList.isAllTest === 0) {
                this.items = JSON.parse(JSON.stringify(this.allItems))
              }else{
                this.$message.error('标准升级，请重新选择项目')
                this.checkList.isAllTest = null
                this.items = []
              }
            }else if(this.isUpgradeStandard === 0){
              //降级，将此标准赋值给显示的标准
              this.isUpgradeStandard = 1
              this.standard = JSON.parse(JSON.stringify(this.nowStandard))
              this.allItems = JSON.parse(JSON.stringify(this.nowStandard.items))
              if (this.checkList.isAllTest === 0) {
                this.items = JSON.parse(JSON.stringify(this.allItems))
              }else{
                this.$message.error('标准降级，请重新选择项目')
                this.checkList.isAllTest = null
                this.items = []
              }
            }
          }
        }
        this.checkList.batchNum = isBlank(this.checkList.batchNumSuffix) ? this.checkList.batchNumPrefix : (this.checkList.batchNumPrefix + '-' + this.checkList.batchNumSuffix)
         const params = {
          checkTypeId: this.checkList.checkTypeId,
          batchNum: this.checkList.batchNum,
         }
         checkBatchNum(params).then(res => {
          if (res.code === CODE_OK) {
            if (res.reCount > 0) {
          this.$message.warning('已存在【'+res.reCount+'】条相同物料编码的请验单信息,请确认是否重复发起.')
            }
          }else{
            this.$message.error('检查物料编码错误，请联系管理员')
          }
         })
      },
      // now > wait true
      conditionOnBatch (now, wait) {
        let yn,yw,mn,mw
        return (yn = parseInt(now.substr(0,2))) > (yw = parseInt(wait.substring(0,2))) ||
        (yn == yw && (mn = parseInt(now.substring(2,4))) > (mw = parseInt(wait.substring(2,4)))) ||
        (yn == yw && mn == mw && parseInt(now.substring(4)) >= parseInt(wait.substring(4)))
      },
      setProcedure() {
        this.zcList.procedureId = this.dataForm.procedure.procedureId
        this.zcList.procedureName = this.dataForm.procedure.procedureName
      },
      setWorkshop() {
        this.zcList.workshopId = this.dataForm.workshop.workshopId
        this.zcList.workshopName = this.dataForm.workshop.workshopName
      },
      setBatchUnit() {
        this.zcList.batchUnitId = this.dataForm.batchUnit.unitId
        this.zcList.batchUnitName = this.dataForm.batchUnit.unitName
      },
      setGetUnit() {
        this.checkList.getUnitId = this.checkList.getUnit.unitId
        this.checkList.getUnitName = this.checkList.getUnit.unitName
      },
      setBatchQuantity() {
        if (!isNumber(this.zcList.batchQuantity)) {
          this.$message.error('请输入数值类型')
          this.zcList.batchQuantity = null
        }
      },
      closeGet() {
        this.getVisible = false
      },
      getOk() {
        if (isBlank(this.checkList.getQuantity) ||isBlank(this.checkList.getUnitId) || isBlank(this.checkList.getUnitName)) {
          this.$message.error("取样量和单位不能为空")
          return
        }else if(isBlank(this.checkList.getDate)){
          this.$message.error("取样日期不能为空")
          return
        }
        // else if(!dateCompare(this.checkList.registCheckDate, this.checkList.getDate)){
        //   this.$message.error("取样日期必须晚于请验日期")
        //   return
        // }
        else{
          this.rag = true
          this.closeGet()
          this.submit()
        }
      },
      showGet() {
        if (isBlank(this.checkList.registCheckDate)) {
          this.$message.error('请选择请检日期')
          $("#registCheckDate").css({"border-color" : "#D08585"})
          return
        }
        this.$set(this.checkList,'getDate', JSON.parse(JSON.stringify(this.checkList.registCheckDate)))
        this.getVisible = true
      }
    }
  }
</script>

<style scoped>
  .el-form-item__content .el-input-group {
    vertical-align: inherit !important;
  }
  >>> .el-input-group__append {
    border: 1px solid #ff0000;
  }
  >>> #batchUnitId::-webkit-input-placeholder {
    color: #ff0000;
  }
  >>> #batchUnitId::-moz-input-placeholder {
    color: #ff0000;
  }
  >>> #batchUnitId::-ms-input-placeholder {
    color: #ff0000;
  }
</style>
